// 获取元素
let $ = ele => document.querySelector(ele);

let main = $('#main');
let info = $('#main .info');
let goTop = $('.footer-top ul').children[2].children[0];

// 加载中
let span = $("header span")
// 在页面未加载完毕之前显示的loading Html自定义内容
let before = $('header span::before');
//监听加载状态改变
document.onreadystatechange = completeLoading;
//加载状态为complete时移除loading效果
function completeLoading() {
    if (document.readyState == "complete") {
        span.parentNode.removeChild(span);
    }
}

// 渲染商品详情
function renderInfoDetail(res) {
    let html = `
    <h4>${res.productName}</h4>
    <div class="other">
    <span>${res.productFrom} | ${res.productTime}</span>
    <i>${res.productTips}</i>
    <p>${res.productPrice}</p>
        </div>
        <div class="content">${res.productInfo}</div>
        ${res.productImg}
        <hr>
        <button>前往购买</button>
        <img src="../images/mmbweixin2.png" alt="">
        ${res.productComment}
        `;
    return html;

}

//获取浏览器的query参数
function getUrlParams() {
    let href = location.href;//获取浏览器的地址
    let regExp = /.+\?(.+)/
    let param = regExp.exec(href)//匹配?后面的参数
    if (!param) {
        console.log('没有query参数');
        return
    }
    param = param[1]
    let paramArr = param.split("&");//多个参数以"&"切割 ?name=李雷&age=30
    console.log(paramArr);//["name=李雷","age=30"]
    let query = {}//声明一个对象
    paramArr.forEach(item => {
        let itemArr = item.split("=");
        console.log(itemArr);
        query[itemArr[0]] = decodeURI(itemArr[1])
    })
    return query
}

//获取浏览器query参数
let query = getUrlParams()
let productid = Number(query.productid);

// 获取商品数据详情
const getInfoDetail = () =>
    ajax({
        url: 'http://chst.vip:1234/api/getdiscountproduct',
        data: { productid: productid }
    })
getInfoDetail().then((res) => {
    info.innerHTML = renderInfoDetail(res.result[0]);
})
localStorage.removeItem('productid')

// 返回顶部
goTop.onclick = function (e) {
    e.preventDefault();
    let distans = document.documentElement.scrollTop
    let distansControl = setInterval(function () {
        distans -= 10
        document.documentElement.scrollTop = distans
        if (distans <= 0) {
            clearInterval(distansControl)
        }
    }, 3)
}